package com.finance.system.configure.mvc;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import javafx.util.Pair;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;

import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class SpringMvcConfiguration extends WebMvcConfigurerAdapter {

    private static List<Pair<String,String>> resourceMapList = new ArrayList<>();

    @Autowired
    private JsonDeserializer LocalDateTimeDeserializer;
    @Autowired
    private JsonSerializer LocalDateTimeSerializer;
    @Autowired
    private HandlerMethodArgumentResolver FinanceHandlerMethodArgumentResolver;


    @Value("${file.base.path}")
    private String fileBasePath;

    static {
        resourceMapList.add(new Pair<>("/img/**","/image/"));
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        for (Pair<String, String> pair : resourceMapList) {
            registry.addResourceHandler(pair.getKey()).addResourceLocations(fileBasePath + pair.getValue());

        }
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDateTimeConverter());
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
                SimpleModule module = new SimpleModule();
                module.addDeserializer(LocalDateTime.class,LocalDateTimeDeserializer);
                module.addSerializer(LocalDateTime.class,LocalDateTimeSerializer);
                objectMapper.registerModule(module);
            }
        }
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(FinanceHandlerMethodArgumentResolver);
    }


}
